package com.spring.nio.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketException;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: YSFY
 * @Date: 2019/11/30 19:28
 * @Pacage_name: com.dh.spring.util
 * @Project_Name: arthas-client
 * @Description: 公共方法
 */
public class BasicUtil {
    private static final Logger logger = LoggerFactory.getLogger(BasicUtil.class);
    private static ByteBuffer buffer = ByteBuffer.allocate(8);
    private static boolean isExist = false;

    //TODO 提供基于两个long型的数据计算百分比
    public static String getPercent(long l1, long l2) {
        DecimalFormat df = new DecimalFormat("0.0000%");//0%、0.000%
        return df.format(((Number) l1).intValue() / ((Number) l2).doubleValue());
    }

    //TODO 判断监听IP地址是否符合
    public static boolean analysisCurrentServerIpService(String checkIp) {
        logger.info("[" + LocalTime.formatDate(LocalDateTime.now()) + "] ----------- 开始本服务器IP地址过滤 -----------");
        try {
            List<String> list = NetUtil.getIpList();
            if(list.isEmpty()) {
                logger.info("[" + LocalTime.formatDate(LocalDateTime.now()) + "] ----------- 本服务器无可用IP地址，服务终止执行 -----------");
                return false;
            }

            list.stream().forEach(ip ->{
                if(ip.contains(checkIp)) {
                    isExist = true;
                    logger.info("[" + LocalTime.formatDate(LocalDateTime.now()) + "] ----------- 服务器监听IP地址 [ " + checkIp + " ] 匹配成功 -----------");
                }
                logger.info("[" + LocalTime.formatDate(LocalDateTime.now()) + "] ----------- [ ip = " + ip + " ] -----------");
            });

        } catch (SocketException e) {
            logger.error("调用analysisCurrentServerIpService方法出现[SocketException]异常，堆栈信息：{} ", e);
        }

        logger.info("[" + LocalTime.formatDate(LocalDateTime.now()) + "] ----------- 结束本服务器IP地址过滤 -----------");
        return isExist;
    }

    //TODO 字符串去掉空格，回车，换行，水平制表符
    public static String replaceBlank(String data) {
        String dest = "";
        if(!"".equals(data)) {
            Pattern p = Pattern.compile("\\s*|\t|\t|\n");
            Matcher m = p.matcher(data);
            dest = m.replaceAll("");
        }

        return dest;
    }

    //TODO long 转 byte[]
    public static byte[] longToBytes(long x) {
        buffer.clear();
        buffer.putLong(0, x);
        return buffer.array();
    }

    //TODO byte[] 转 long
    public static long bytesToLong(byte[] bytes) {
        buffer.put(bytes, 0, bytes.length);
        buffer.flip();//need flip
        long result = buffer.getLong();
        buffer.clear();
        return result;
    }

    //TODO int 转 byte[]
    public static byte[] intToBytes(int value) {
        byte[] result = new byte[4];
        // 由高位到低位
        result[0] = (byte) ((value >> 24) & 0xFF);
        result[1] = (byte) ((value >> 16) & 0xFF);
        result[2] = (byte) ((value >> 8) & 0xFF);
        result[3] = (byte) (value & 0xFF);
        return result;
    }

    //TODO byte[] 转 int
    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        // 由高位到低位
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (bytes[i] & 0x000000FF) << shift;// 往高位游
        }
        return value;
    }

    /**
     * byte[]转short
     * @param b
     * @return
     */
    public static short byte2short(byte[] b){
        short l = 0;
        for (int i = 0; i < 2; i++) {
            l<<=8;
            l |= (b[i] & 0xff);
        }
        return l;
    }

    /**
     * short转byte[]
     * @param s
     * @return
     */
    public static byte[] unsignedShortToByte2(int s) {
        byte[] targets = new byte[2];
        targets[0] = (byte) (s >> 8 & 0xFF);
        targets[1] = (byte) (s & 0xFF);
        return targets;
    }
}
